package com.atguigu.srb.sms.controller.api;

import com.atguigu.common.exception.Assert;
import com.atguigu.common.result.R;
import com.atguigu.common.result.ResponseEnum;
import com.atguigu.common.utils.RandomUtils;
import com.atguigu.common.utils.RegexValidateUtils;
import com.atguigu.srb.sms.client.CoreUserInfoClient;
import com.atguigu.srb.sms.service.SmsService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;
import javax.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author lupengning
 * @version 1.0
 * @description: 短信管理
 * @date 2021/6/4 19:38
 */
@RestController
@Slf4j
@Api(tags = "短信管理")
//@CrossOrigin
@RequestMapping("/api/sms")
public class ApiSmsController {

  @Resource
  private SmsService smsService;

  @Resource
  private CoreUserInfoClient coreUserInfoClient;

  @Resource
  private RedisTemplate redisTemplate;

  @GetMapping("send/{mobile}")
  @ApiOperation("发送短信")
  public R sendMessage(@ApiParam(value = "手机号码", required = true) @PathVariable String mobile) {
    // 校验手机号码
    Assert.notEmpty(mobile, ResponseEnum.MOBILE_NULL_ERROR);
    Assert.isTrue(RegexValidateUtils.checkCellphone(mobile),ResponseEnum.MOBILE_ERROR);

    //判断手机号码是否被注册
    boolean mobileIsExit = coreUserInfoClient.checkMobile(mobile);
    Assert.isTrue(!mobileIsExit,ResponseEnum.MOBILE_EXIST_ERROR);

    String code = RandomUtils.getFourBitRandom();
    HashMap<String, Object> map = new HashMap<>();
    map.put("code", code);
    // smsService.send(mobile, SmsProperties.TEMPLATE_CODE,map);

    //将验证码存入到redis中
    redisTemplate.opsForValue().set("srb:sms:code:" + mobile,code,5, TimeUnit.MINUTES);
    return R.ok().message("短信发送成功");
  }
}
